package com.hspedu.furns.web;

import com.google.gson.Gson;
import com.hspedu.furns.entity.Member;
import com.hspedu.furns.service.MemberService;
import com.hspedu.furns.service.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;


/**
 * @author 徐
 * @version 1.0
 * web层servlet减肥
 * LoginServlet,RegisterServlet 合并为 MemberServlet
 * 处理和member相关的请求
 */
public class MemberServlet extends BasicServlet {
    //定义一个service属性
    private MemberService memberService = new MemberServiceImpl();

//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //System.out.println("MemberServlet被调用...");
//        if (request.getParameter("action").equals("login")){
//            login(request,response);
//        }else if (request.getParameter("action").equals("register")){
//            register(request,response);
//        }else {
//            //提示信息
//            response.getWriter().write("请求参数action错误");
//        }
//    }


    /**
     * LoginServlet的作用，登陆业务
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //说明:如果在登录页面, 用户没有输入内容，就直接提交，后台接收到的是""
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //创建 Member对象
        Member member = memberService.login(new Member(null, username, password, null));
        //调用memberService判断
        if (member != null) {//("登陆成功");
            //创建session对象，将member对象放入
            HttpSession session = request.getSession();
            session.setAttribute("member",member);
            //登陆成功，跳转页面
            request.getRequestDispatcher("/views/member/login_ok.jsp")
                    .forward(request,response);
        }else {//("登陆失败");
            request.setAttribute("msg","用户名或密码错误");
            request.setAttribute("username",username);
            request.getRequestDispatcher("/views/member/login.jsp")
                    .forward(request,response);
        }
    }

    /**
     * RegisterServlet的作用，注册业务
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收用户注册信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        //接收输入的验证码
        String code = request.getParameter("code");
        //从session中获取图片显示的的验证码
        String token = (String)request.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        //立即删除session验证码->防止该验证码被重复使用
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //如果token为空，并且和用户提交的验证码一致,就继续
        if (token != null && code.equalsIgnoreCase(token)) {//忽略大小写

            //判断用户名是否可用
            if (!memberService.isExistsUsername(username)) {
                //添加用户
                //System.out.println("用户名 " + username +" 不存在，可以注册");
                Member member = new Member(null, username, password, email);
                if (memberService.registerMember(member)) {
                    request.setAttribute("username",username);
                    //请求转发
                    request.getRequestDispatcher("/views/member/register_ok.jsp")
                            .forward(request, response);
                } else {//发生错误
                    //System.out.println("注册error");
                    //请求转发
                    request.getRequestDispatcher("/views/member/register_fail.jsp")
                            .forward(request, response);
                }
            } else {//已经注册过,不可以注册
                //返回注册页面
                //后面可以加入提示信息
                //System.out.println("用户名 " + username +" 已经存在，不可以注册");
                //请求转发
                request.getRequestDispatcher("/views/member/login.jsp")
                        .forward(request, response);
            }
        }else {//验证码不正确的情况
            request.setAttribute("msg","验证码不正确~");
            //带回信息，要显示到注册页面
            request.setAttribute("active","register");
            //当验证码输入错误时，回显信息
            request.setAttribute("username",username);
            request.setAttribute("password",password);
            request.setAttribute("repassword",request.getParameter("repassword"));
            request.setAttribute("email",email);
            //请求转发
            request.getRequestDispatcher("/views/member/login.jsp")
                    .forward(request, response);
        }
    }

    /**
     * 注销登录
     * 清空session信息，使得首页重新登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //清空session信息，自己写的
        //request.getSession().removeAttribute("member");
        //销毁当前用户session，老韩
        //这种写法用户退出时，购物车信息就删除了
        request.getSession().invalidate();
        //重定向到首页，转发之后首页 url 会带 logout 信息
        // index.jsp 路径可以去掉，默认也会找到
        response.sendRedirect(request.getContextPath());
    }

    /**
     * 验证某个用户名是否存在数据库中
     * @param request
     * @param response
     */
    public void isExistUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取用户名
        String username = request.getParameter("username");
        //2.调用service方法，判断用户名是否存在
        boolean isExistsUsername = memberService.isExistsUsername(username);
        //3. 思路
        //(1). 如何返回json格式 [不要乱写, 要根据前端的需求来玩]
        //(2). 因为目前前端和后端都是我们自己写, 我们自己定
        //(3) {"isExist":false};

        //4. 先使用最最简单拼接 => 一会老师改进[可扩展], 印象就会非常深刻[一通百通]
        //String resultJson = "{\"isExist\":"+isExistsUsername+"}";

        //返回json
        //response.getWriter().write(resultJson);

        //5.使用集合，创建json
        HashMap<String, Object> resultMap = new HashMap<>();
        //6.将信息放入集合
        resultMap.put("isExist",isExistsUsername);
        //7.将集合转成json格式
        String resultJson = new Gson().toJson(resultMap);
        //返回json
        response.getWriter().write(resultJson);
        
    }

    /**
     * ajax校验验证码是否正确
     * 即不提交也能显示正确与否
     * 返回json格式
     * @param request
     * @param response
     */
    public void isCorrectCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从session中获取图片显示的的验证码
        String token = (String)request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //5.使用集合，创建json
        HashMap<String, String> resultMap = new HashMap<>();
        //6.将信息放入集合
        resultMap.put("token",token);
        //7.将集合转成json格式
        String resultJson = new Gson().toJson(resultMap);
        //返回json
        response.getWriter().write(resultJson);

    }

}
